import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { queryArticleList, queryHotArticleList } from "@/api/article.api";
import { ArticleList } from "@/types/article";

/**
 * 异步获取热门文章列表
 */
export const getHotArticleList = createAsyncThunk(
  "article/getHotArticleList",
  async (): Promise<ArticleList> => {
    const res = await queryHotArticleList();
    if (res.code === 200) {
      return res.data || [];
    }
    return [];
  }
);

/**
 * 异步获取顶级文章列表
 */
export const getTopArticleList = createAsyncThunk(
  "article/getTopArticleList",
  async (): Promise<ArticleList> => {
    const params = {
        pageNo: 1,
        pageSize: 10,
      };
    const res = await queryArticleList(params);
    if (res.code === 200) {
      return res.data ? res.data.rows : [];
    }
    return [];
  }
);

/**
 * 文章状态管理器
 */
export const articleSlice = createSlice({
  name: "article",
  initialState: {
    hotArticleList: <ArticleList>[],
    topArticleList: <ArticleList>[],
  },
  reducers: {},
  extraReducers(builder) {
    // 当获取热门文章列表成功时，更新状态
    builder
    .addCase(getHotArticleList.fulfilled, (state, action) => {
      state.hotArticleList = action.payload;
    });
    // 当获取顶级文章列表成功时，更新状态
    builder.addCase(getTopArticleList.fulfilled, (state, action) => {
      state.topArticleList = action.payload;
    });
  },
});

// Action creators are generated for each case reducer function
//   export const {  } = webInfoSlice.actions

export default articleSlice.reducer;